package cn.wyj.org.service.impl;

import cn.wyj.basic.query.BaseQuery;
import cn.wyj.basic.service.impl.BaseServiceImpl;
import cn.wyj.basic.util.MD5Utils;
import cn.wyj.basic.util.PageList;
import cn.wyj.basic.util.StrUtils;
import cn.wyj.org.domain.Employee;
import cn.wyj.org.mapper.EmployeeMapper;
import cn.wyj.org.query.EmployeeQuery;
import cn.wyj.org.service.EmployeeService;
import cn.wyj.system.mapper.RoleMapper;
import cn.wyj.user.domain.Logininfo;
import cn.wyj.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Employee> findEmpByDeptId(Long deptId) {
        return employeeMapper.findEmpByDeptId(deptId);
    }

    @Override
    public void add(Employee employee) {
        // 生成盐值 给密码加密
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(salt + employee.getPassword());
        employee.setSalt(salt);
        employee.setPassword(password);

        // 关联logininfo ,将employee数据复制到Logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfoMapper.add(logininfo);

        Long id = logininfo.getId();

        employee.setLogininfoId(id);
        super.add(employee);

    }

    @Override
    public void update(Employee employee) {


        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        Long logininfoId = employee.getLogininfoId();
        logininfo.setId(logininfoId);

        super.update(employee);
        logininfoMapper.update(logininfo);
    }

    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        PageList<Employee> employeePageList = super.queryByPage(query);
//        List<Employee> rows = employeePageList.getRows();
//        for (Employee row : rows) {
//            Long id = row.getId();
//            Long rid =  roleMapper.findRIdByEmpId(id);
//            row.setRoles(rid);
//        }

        return employeePageList;
    }
}
